/**
 * 文档列表Hook
 * 提供文档列表管理功能
 */

import { useState, useCallback, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'
import { StorageFactory } from '../../services/storage'
import { ContentType } from '../../types/document'
import type { ContentListItem, StorageError } from '../../services/storage/types'
import { generateContentId } from '../../utils/documentUtils'

export function useDocumentList() {
  const navigate = useNavigate()
  const [documents, setDocuments] = useState<ContentListItem[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<StorageError | null>(null)
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())

  const loadDocuments = useCallback(async () => {
    setIsLoading(true)
    setError(null)

    console.log('[DocumentList] 加载文档列表')

    try {
      // 检查存储是否已初始化
      let storage
      try {
        storage = StorageFactory.getAdapter()
      } catch (err) {
        console.warn('[DocumentList] 存储未初始化,等待初始化完成')
        throw new Error('存储未初始化')
      }

      // 调用存储服务获取所有文档
      const result = await storage.getContents({
        type: [ContentType.TEXT_DOCUMENT],
        sortBy: 'updatedAt',
        sortOrder: 'desc'
      })

      setIsLoading(false)

      if (!result.ok) {
        console.error('[DocumentList] 加载失败', result.error)
        setError(result.error)
        return
      }

      console.log('[DocumentList] 加载成功', result.data.length, '个文档')
      setDocuments(result.data)
    } catch (error) {
      console.error('[DocumentList] 加载异常', error)
      setIsLoading(false)
      setError({
        code: 'UNKNOWN' as any,
        message: error instanceof Error ? error.message : '加载失败'
      })
    }
  }, [])

  const deleteDocument = useCallback(async (id: string) => {
    console.log('[DocumentList] 删除文档', id)

    try {
      const storage = StorageFactory.getAdapter()
      const result = await storage.removeContent(id)

      if (!result.ok) {
        message.error(result.error.message)
        return false
      }

      // 从列表中移除
      setDocuments(prev => prev.filter(doc => doc.id !== id))
      message.success('文档已删除')
      console.log('[DocumentList] 删除成功')
      return true
    } catch (error) {
      console.error('[DocumentList] 删除异常', error)
      message.error(error instanceof Error ? error.message : '删除失败')
      return false
    }
  }, [])

  const batchDeleteDocuments = useCallback(async (ids: string[]) => {
    console.log('[DocumentList] 批量删除文档', ids.length, '个')

    try {
      const storage = StorageFactory.getAdapter()
      let successCount = 0
      let failCount = 0

      // 逐个删除
      for (const id of ids) {
        const result = await storage.removeContent(id)
        if (result.ok) {
          successCount++
        } else {
          failCount++
          console.error('[DocumentList] 删除失败', id, result.error)
        }
      }

      // 从列表中移除成功删除的文档
      setDocuments(prev => prev.filter(doc => !ids.includes(doc.id) || failCount > 0))

      // 清空选中状态
      setSelectedIds(new Set())

      if (failCount === 0) {
        message.success(`已删除 ${successCount} 个文档`)
      } else {
        message.warning(`成功删除 ${successCount} 个，失败 ${failCount} 个`)
      }

      console.log('[DocumentList] 批量删除完成', { successCount, failCount })
      return successCount > 0
    } catch (error) {
      console.error('[DocumentList] 批量删除异常', error)
      message.error(error instanceof Error ? error.message : '批量删除失败')
      return false
    }
  }, [])

  const toggleSelectDocument = useCallback((id: string) => {
    setSelectedIds(prev => {
      const newSet = new Set(prev)
      if (newSet.has(id)) {
        newSet.delete(id)
      } else {
        newSet.add(id)
      }
      return newSet
    })
  }, [])

  const selectAllDocuments = useCallback(() => {
    setSelectedIds(new Set(documents.map(doc => doc.id)))
  }, [documents])

  const clearSelection = useCallback(() => {
    setSelectedIds(new Set())
  }, [])

  const createNewDocument = useCallback(() => {
    const newId = generateContentId(ContentType.TEXT_DOCUMENT)
    console.log('[DocumentList] 创建新文档', newId)
    navigate(`/text/editor/${newId}`)
  }, [navigate])

  const openDocument = useCallback((id: string) => {
    console.log('[DocumentList] 打开文档', id)
    navigate(`/text/editor/${id}`)
  }, [navigate])

  useEffect(() => {
    // 延迟加载,确保存储已初始化
    const timer = setTimeout(() => {
      loadDocuments()
    }, 100)

    return () => clearTimeout(timer)
  }, [loadDocuments])

  // 监听文档保存事件，自动刷新列表
  useEffect(() => {
    const handleDocumentSaved = () => {
      console.log('[DocumentList] 检测到文档保存，刷新列表')
      loadDocuments()
    }

    window.addEventListener('document:saved', handleDocumentSaved)
    return () => window.removeEventListener('document:saved', handleDocumentSaved)
  }, [loadDocuments])

  return {
    documents,
    isLoading,
    error,
    selectedIds,
    loadDocuments,
    deleteDocument,
    batchDeleteDocuments,
    toggleSelectDocument,
    selectAllDocuments,
    clearSelection,
    createNewDocument,
    openDocument
  }
}
